#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct node 
{
  int data;
  struct node * next;
};

struct stack
{
  struct node * top;
};

int gettop(struct stack * src)
{
  if (src->top == NULL) {
    printf("The stack is empty.\n");
    return -1;
  }

  return src->top->data;
}

struct stack * create()
{
  struct stack * src;

  src = (struct stack *) malloc (sizeof(struct stack));
  src->top = NULL;

  return src;
}

struct stack * push(struct stack * src, int value)
{
  struct node * des;

  des = malloc (sizeof(struct node));
  assert(des != NULL);
  des->data = value;
  des->next = NULL;

  des->next = src->top; // 存储当前栈top地址
  src->top = des; // 指针指向新节点des. top 更新为最新

  return src;
}

struct stack * pop(struct stack * src, int * e)
{
  struct node * des;

  des = src->top;
  *e = src->top->data;
  src->top = src->top->next; // top 指针下移
  free(des);

  return src;
}

int empty(struct stack * src)
{
  return src->top == NULL;
}

int display(struct stack * src)
{
  struct node * des;

  if (src->top == NULL) {
    printf("the stack is empty.\n");
    return 0;
  }
  else {
    des = src->top;
    printf("the stack is : ");
    while (des != NULL) {
      printf(" %d ", des->data);
      des = des->next;
    }
    printf("\n\n");
  }
}

int main()
{
  struct stack * src;
  int e;

  src = create();
  src = push(src, 1);
  src = push(src, 2);
  src = push(src, 3);
  src = push(src, 4);
  display(src);

  src = pop(src, &e);
  display(src);

}
